//
//  BranchListViewController.m
//  takeout
//
//  Created by Mac on 13-1-23.
//
//

#import "BranchListViewController.h"
#import "DetailShopViewController.h"
#import "Supplier.h"
#import "SupplierCategory.h"
#import "PublicFunction.h"
#import "UICustomImageView.h"
#import "Constants.h"
#import "AdManager.h"
#import "Ad.h"
#import "FMDBAdManager.h"
#import "MobClick.h"
#import "Constants.h"
#import "UserFeedBackController.h"


@interface BranchListViewController (private)
- (void)refresh;
- (void)stopLoading;
- (void)startLoading;
@end
@implementation BranchListViewController
@synthesize manager;
@synthesize suppliers;
@synthesize currentPage;
@synthesize tableViews;
@synthesize appDelegate;
@synthesize _refreshHeaderView;
@synthesize _reloading;
@synthesize scrollView;
@synthesize timeCount;
@synthesize fmdbAdManager;
@synthesize adsCount;
@synthesize conditions;
@synthesize searchType;
@synthesize address;
@synthesize isSelling;
@synthesize tempSupId;
@synthesize tempSupName;

@synthesize branchs;
@synthesize isTouched;

//初始化导航栏
-(void)initNav{
    //定义导航栏左侧按钮
    UIButton *leftButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 54, 27)];
    NSString *filePath2=[[NSBundle mainBundle] pathForResource:@"navLeftBtn" ofType:@"png"];
    [leftButton setBackgroundImage:[UIImage imageWithContentsOfFile:filePath2] forState:UIControlStateNormal];
    [leftButton setTitle:@"返 回" forState:UIControlStateNormal];
    leftButton.titleLabel.font=[UIFont fontWithName:@"Helvetica-Bold" size:14];
    [leftButton addTarget:self action:@selector(backButtonPressdDelay:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    self.navigationItem.leftBarButtonItem = leftItem;
}

- (void)backButtonPressdDelay:(id)sender{
    NSURL *system_sound_url=[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"1248" ofType:@"wav"]];
    SystemSoundID system_sound_id;
    AudioServicesCreateSystemSoundID((__bridge CFURLRef)system_sound_url, &system_sound_id);
    AudioServicesPlaySystemSound(system_sound_id);
    
    [self performSelector:@selector(backButtonPressd:) withObject:sender afterDelay:0.1];
}

- (void)backButtonPressd:(id)sender{
    //将当前视图推出栈，程序将进入上一视图
    [self.navigationController popViewControllerAnimated:YES];
}


-(void)showHUD{
    MBProgressHUD *HUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
	[self.navigationController.view addSubview:HUD];
	HUD.dimBackground = YES;
    HUD.delegate = self;
    [HUD showWhileExecuting:@selector(myTask) onTarget:self withObject:nil animated:YES];
}

- (void)myTask {
    currentPage = 1;
    
    
    if (branchs.count==0) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"没有该类型的商家" delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
        alertView.tag=2;
        [alertView show];
        return;
    }
//    else{
//        //初始化刷新cell
//        if([branchs count]>=SSsupplierCount){
//            [tableViews reloadData];
//            [_refreshHeaderView removeFromSuperview];
//            _refreshHeaderView.frame=CGRectMake(0, tableViews.contentSize.height, 320, 250);
//            [tableViews addSubview:_refreshHeaderView];
//            [_refreshHeaderView refreshLastUpdatedDate];
//        }
//        else{
//            [tableViews reloadData];
//            _refreshHeaderView.frame=CGRectMake(0, 600, 320, 250);
//        }
//        NSString *source = (NSString *)[recieveDictionary objectForKey:@"source"];
//        }
}
















- (void)viewDidLoad {
    [super viewDidLoad];
    
    //添加手势
    //后退
    UISwipeGestureRecognizer *recognizer;
    recognizer = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(handleSwipeFrom:)];
    [recognizer setDirection:(UISwipeGestureRecognizerDirectionRight)];
    [[self view] addGestureRecognizer:recognizer];
    
    //设置视图title
    self.title=@"商家列表";
    //初始化导航栏
    [self initNav];
    //初始化商家管理类
    manager = [[SupplierManager alloc] init];
    //    fmdbSupplierManager=[[FMDBSupplierManager alloc]init];
    appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    
    
    
    NSInteger tempHeight=SSiphoneType==0?365:365+IOS5HEIGHT;
    tableViews=[[UITableView alloc] initWithFrame:CGRectMake(0, 0, 320, tempHeight)];
    //    tableViews=[[UITableView alloc] initWithFrame:CGRectMake(0, 55, 320, 312)];
    
    
    tableViews.backgroundColor=[UIColor whiteColor];
    //添加到view窗体上
    [self.view addSubview:tableViews];
    tableViews.delegate=self;
    tableViews.dataSource=self;
    tableViews.contentSize =CGSizeMake(320, [branchs count]*64);
    //减慢tableview的滚动速度，正常值为1.f
    tableViews.decelerationRate=0.5f;
    

    

    [self showHUD];
}

- (void)viewWillAppear:(BOOL)animated{
    //设置显示导航栏
    self.navigationController.navigationBarHidden = NO;
    isTouched=YES;
}

//手势
-(void)handleSwipeFrom:(UISwipeGestureRecognizer *)recognizer{
    //后退
    if(recognizer.direction==UISwipeGestureRecognizerDirectionRight) {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

/**************************/
/*       商家列表视图       */
/*************************/

//返回表试图分区行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [branchs count]+1;
}

-(void)showFeedBackViewDelay:(id)sender{
    NSURL *system_sound_url=[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"1248" ofType:@"wav"]];
    SystemSoundID system_sound_id;
    AudioServicesCreateSystemSoundID((__bridge CFURLRef)system_sound_url, &system_sound_id);
    AudioServicesPlaySystemSound(system_sound_id);
    [self performSelector:@selector(showFeedBackView) withObject:NULL afterDelay:0.1];
}


-(void)showFeedBackView{
    if(isTouched)
    {
        isTouched=NO;


        
    //创建新的试图并将试图推入栈中
    UserFeedBackController *userFeedBackController = [[UserFeedBackController alloc] init];
    NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithCapacity :2];
    [dictionary setObject:@"F" forKey:@"type"];
    [dictionary setObject:@"我有意见" forKey:@"title"];
    [userFeedBackController setRecieveDictionary:dictionary];
    [self.navigationController pushViewController: userFeedBackController animated:YES];
    }
}

//设置表试图每行显示的内容
- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger index=indexPath.row;
//    Supplier *supplier=[suppliers objectAtIndex:index];
    static NSString *CellIdentifier = @"CustomCell";
    UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    
	if(cell == nil) {
		cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    cell.opaque=YES;
 
    
    if(index==[branchs count]){
        UILabel *addLabel = (UILabel *)[cell.contentView viewWithTag:301];
        if (addLabel == nil) {
                        addLabel.font=[UIFont fontWithName:@"Helvetica-Bold" size:16];
            addLabel.opaque=YES;

            addLabel = [[UILabel alloc] initWithFrame:CGRectMake(40, 24, 153, 16)];
            addLabel.tag = 301;
            [addLabel setText:@"没有找到想要的？请联系我们"];
            [cell.contentView addSubview:addLabel];
        }
        [addLabel setText:@"没有找到想要的？请"];
        

        
        
        
            UIButton *phoneButton = (UIButton *)[cell.contentView viewWithTag:302];
            if (phoneButton == nil)
            {
                phoneButton = [UIButton buttonWithType:UIButtonTypeCustom];
                phoneButton.opaque=YES;
                [phoneButton setFrame:CGRectMake(194, 18, 100, 30)];
        
                NSString *filePath=[[NSBundle mainBundle] pathForResource:@"buttonBg02" ofType:@"png"];
                UIImage *image = [UIImage imageWithContentsOfFile:filePath];
                [phoneButton setBackgroundImage:image forState:UIControlStateNormal];
                               [phoneButton setTitle:@"反馈给我们" forState:UIControlStateNormal];
                        phoneButton.titleLabel.font=[UIFont fontWithName:@"Helvetica-Bold" size:12];
                phoneButton.tag = 302;
                [phoneButton addTarget:self action:@selector(showFeedBackViewDelay:) forControlEvents:UIControlEventTouchUpInside];
                [cell.contentView addSubview:phoneButton];
                //点击拨号按钮直接拨号
            }
        
    
    }
    else{
        //    UICustomImageView *imageView = (UICustomImageView *)[cell.contentView viewWithTag:100];
        //    if (imageView == nil) {
        //        imageView = [[UICustomImageView alloc] initWithFrame:CGRectMake(8, 2, 60, 60)];
        //        imageView.opaque=YES;
        //        [imageView setContentMode:UIViewContentModeScaleAspectFit];
        //        [imageView setUserInteractionEnabled:NO];
        //        [imageView setTag:100];
        //        [cell.contentView addSubview:imageView];
        //    }
        //    [imageView setImage:nil];
        //    [imageView setImageURL:supplier.imgUrl];
        
        
        
    UILabel *shopNameLabel = (UILabel *)[cell.contentView viewWithTag:200];
    if (shopNameLabel == nil) {
        //标题2
        shopNameLabel.font=[UIFont fontWithName:@"Helvetica-Bold" size:16];
        shopNameLabel.opaque=YES;
        shopNameLabel = [[UILabel alloc] initWithFrame:CGRectMake(85, 5, 220, 16)];
        //自定义颜色
        [shopNameLabel setTextColor:[UIColor colorWithRed:255.0/255.0 green:111.0/255.0 blue:6.0/255.0 alpha:1.0f]];
        [shopNameLabel setText:[branchs objectAtIndex:index]];
        shopNameLabel.tag = 200;
        [cell.contentView addSubview:shopNameLabel];
    }
    [shopNameLabel setText:[branchs objectAtIndex:index]];
//
//    UILabel *shopTypeLable=(UILabel *)[cell.contentView viewWithTag:202];
//    if (shopTypeLable == nil) {
//        shopTypeLable = [[UILabel alloc] initWithFrame:CGRectMake(80, 30, 160, 12)];
//        shopTypeLable.opaque=YES;
//        shopTypeLable.font=[UIFont fontWithName:@"Helvetica" size:12];
//        shopTypeLable.tag = 202;
//        [cell.contentView addSubview:shopTypeLable];
//    }
//    //    NSString *supplierCategoryName = [NSString stringWithFormat:@"【%@】",supplier.supplierCategoryName];
//    NSString *supplierCategoryName = [[NSString alloc] initWithFormat:@"【%@】",supplier.supplierCategoryName];
//    [shopTypeLable setText:supplierCategoryName];
//    
//    UILabel *shopAvgPriceLable=(UILabel *)[cell.contentView viewWithTag:203];
//    if (shopAvgPriceLable == nil) {
//        shopAvgPriceLable = [[UILabel alloc] initWithFrame:CGRectMake(165, 30, 100, 12)];
//        shopAvgPriceLable.opaque=YES;
//        shopAvgPriceLable.font=[UIFont fontWithName:@"Helvetica" size:12];
//        //自定义颜色
//        [shopAvgPriceLable setTextColor:[UIColor colorWithRed:255.0/255.0 green:111.0/255.0 blue:6.0/255.0 alpha:1.0f]];
//        [shopAvgPriceLable setBackgroundColor:[UIColor clearColor]];
//        shopAvgPriceLable.tag = 203;
//        [cell.contentView addSubview:shopAvgPriceLable];
//    }
//    NSString *avgPrice=[[NSString alloc]initWithFormat:@"人均: %.2f",supplier.avgPrice];
//    [shopAvgPriceLable setText:avgPrice];
//    
//    UILabel *shopAddressLabel = (UILabel *)[cell.contentView viewWithTag:201];
//    if (shopAddressLabel == nil) {
//        shopAddressLabel = [[UILabel alloc] initWithFrame:CGRectMake(85, 48, 160, 12)];
//        shopAddressLabel.opaque=YES;
//        shopAddressLabel.font=[UIFont fontWithName:@"Helvetica" size:12];
//        [shopAddressLabel setBackgroundColor:[UIColor clearColor]];
//        shopAddressLabel.tag = 201;
//        [cell.contentView addSubview:shopAddressLabel];
//    }
//    NSString *tempAddress=[[NSString alloc]initWithFormat:@"地址: %@",supplier.address];
//    [shopAddressLabel setText:tempAddress];
//    
//    UIButton *phoneButton = (UIButton *)[cell.contentView viewWithTag:300];
//    if (phoneButton == nil)
//    {
//        phoneButton = [UIButton buttonWithType:UIButtonTypeCustom];
//        phoneButton.opaque=YES;
//        [phoneButton setFrame:CGRectMake(240, 27, 30, 30)];
//        
//        NSString *filePath=[[NSBundle mainBundle] pathForResource:@"phoneImg" ofType:@"png"];
//        UIImage *image = [UIImage imageWithContentsOfFile:filePath];
//        [phoneButton setBackgroundImage:image forState:UIControlStateNormal];
//        phoneButton.tag = 300;
//        [phoneButton addTarget:self action:@selector(callAction:event:) forControlEvents:UIControlEventTouchUpInside];
//        [cell.contentView addSubview:phoneButton];
//        //点击拨号按钮直接拨号
//    }
    //设置cell的样式，带箭头
    [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
    cell.tag = 460;
    }
    [cell setSelectionStyle:UITableViewCellSelectionStyleGray];
    return cell;
}




//定义点击拨号按钮时的操作
- (void)callAction:(id)sender event:(id)event{
    NSURL *system_sound_url=[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"1248" ofType:@"wav"]];
    SystemSoundID system_sound_id;
    AudioServicesCreateSystemSoundID((__bridge CFURLRef)system_sound_url, &system_sound_id);
    AudioServicesPlaySystemSound(system_sound_id);
    
    NSSet *touches = [event allTouches];
    UITouch *touch = [touches anyObject];
    CGPoint currentTouchPosition = [touch locationInView:tableViews];
    NSIndexPath *indexPath = [tableViews indexPathForRowAtPoint: currentTouchPosition];
    if (indexPath == nil) {
        return;
    }
    NSUInteger  row = [indexPath row];
    Supplier *rowData = [suppliers objectAtIndex:row];
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"拨打电话" message:@"请选择要拨打的号码" delegate:self cancelButtonTitle:@"取  消" otherButtonTitles:nil];
    if(rowData.phone.length != 0){
        [alert addButtonWithTitle:rowData.phone];
    }
    if(rowData.phone2.length != 0){
        [alert addButtonWithTitle:rowData.phone2];
    }
    if(rowData.telephone.length != 0){
        [alert addButtonWithTitle:rowData.telephone];
    }
    if(rowData.telephone2.length != 0){
        [alert addButtonWithTitle:rowData.telephone2];
    }
    alert.tag = 1;
    //点击拨号按钮时，将当前行的商家ID和商家NAME保存到变量中
    tempSupId = [[NSString alloc] initWithFormat:@"%d",rowData.supplierId];
    tempSupName = rowData.supplierName;
	[alert show];
}

//根据被点击按钮的索引处理点击事件
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    //tag为1时为点击拨号按钮时弹出的对话框
    if(alertView.tag == 1){
        NSString *number = [alertView buttonTitleAtIndex:buttonIndex];
        //phoneNumber为号码字符串
        NSString *phoneNumber = [[NSString alloc] initWithFormat:@"tel://%@",number];
        //统计拨打电话的次数到友盟
        NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                              tempSupId,@"商家ID",tempSupName,@"商家名称", nil];
        [MobClick event:@"shopCallActionNew" attributes:dict];
        //拨号
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:phoneNumber]];
    }
    //找不到结果，返回上页
    if(alertView.tag==2){
        //将当前视图推出栈，程序将进入上一视图
        [self.navigationController popViewControllerAnimated:YES];
    }
}

//选中Cell响应事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSURL *system_sound_url=[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"1248" ofType:@"wav"]];
    SystemSoundID system_sound_id;
    AudioServicesCreateSystemSoundID((__bridge CFURLRef)system_sound_url, &system_sound_id);
    AudioServicesPlaySystemSound(system_sound_id);
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];//选中后的反显颜色即刻消失
    
    
    if(indexPath.row==[branchs count]){
        
    }
    else{
    NSString *supplierId = [[NSString alloc] initWithFormat:@"%d",460];
    Supplier *supplierDetail= [manager getSupplierDetailById:supplierId];
    //创建新的试图并将试图推入栈中
    DetailShopViewController *detailShopViewController = [[DetailShopViewController alloc]init];
    NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithCapacity :2];
    [dictionary setObject:supplierId forKey:@"supId"];
    [dictionary setObject:supplierDetail forKey:@"Supplier"];
    [dictionary setObject:supplierDetail.supplierName forKey:@"supName"];
    [dictionary setObject:@"shopListCellSelectedNew" forKey:@"source"];//用户统计到友盟时的来源判断
    [detailShopViewController setRecieveDictionary:dictionary];
    [self.navigationController pushViewController: detailShopViewController animated:YES];
    }
}

//设置表试图行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 64;
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

-(void)viewDidUnload{
    self.manager=nil;
    self.suppliers=nil;
    self.tableViews=nil;
    self.appDelegate=nil;
    self._refreshHeaderView=nil;
    self.scrollView=nil;
    self.fmdbAdManager=nil;
    self.conditions=nil;
    self.searchType=nil;
    self.address=nil;
    self.isSelling=nil;
    self.tempSupId=nil;
    self.tempSupName=nil;
    [super viewDidUnload];
}

//- (void)dealloc {
//
//}
@end
